package com.point_of_sale.product_loader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import com.point_of_sale.product.NormalProduct;
import com.point_of_sale.product.Product;
import com.point_of_sale.product.WholesaleProduct;

// This class builds the product list using comma-separated plain text
public class PlainTextProductLoader implements ProductLoader 
{
	private final String PLAIN_TEXT_DELIMITER = ",";
	
	@Override
	public HashMap<String, Product> getProducts(String location) 
	{
		HashMap<String, Product> products = new HashMap<String, Product>();
		
		try
		{
			String line;
			BufferedReader reader = new BufferedReader(new FileReader(location));
			
			while((line = reader.readLine()) != null)
			{
				String[] parsedLine = line.split(PLAIN_TEXT_DELIMITER);
				
				if(parsedLine.length == 2)
				{
					NormalProduct p = new NormalProduct();
					p.setProductCode(parsedLine[0]);
					p.setPrice(Float.parseFloat(parsedLine[1]));
					products.put(p.getProductCode(), p);
				}
				else
				{
					WholesaleProduct p = new WholesaleProduct();
					p.setProductCode(parsedLine[0]);
					p.setPrice(Float.parseFloat(parsedLine[1]));
					p.setWholesaleNumber(Integer.parseInt(parsedLine[2]));
					p.setWholesalePrice(Float.parseFloat(parsedLine[3]));
					products.put(p.getProductCode(), p);
				}
			}
		}
		catch(IOException e)
		{
			System.err.println(e.getMessage());
		}
		
		return products;
	}
}
